package com.ternnetwork.workflow.controller;

import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ternnetwork.commons.model.http.BaseResponse;
import com.ternnetwork.workflow.dto.ProcessDefinitionQueryDto;
import com.ternnetwork.workflow.service.ProcessDefinitionService;


/**
 * 流程定义控制器
 * @author xuwenfeng
 *
 */
@Controller
@RequestMapping("/process/definition/*")
public class ProcessDefinitionController {
	
	
	@Autowired
	private ProcessDefinitionService processDefinitionService;
	

	/**
	 * 挂起一个流程定义
	 * @param id
	 * @return
	 */
	@RequestMapping("/suspend")
	public @ResponseBody BaseResponse suspend(String id){
		return processDefinitionService.suspendProcessDefinitionById(id);
	}
	
	
	/**
	 * 激活一个已被挂起的流程定义
	 * @param id
	 * @return
	 */
	@RequestMapping("/activate")
	public @ResponseBody BaseResponse activate(String id) {
		return processDefinitionService.activateProcessDefinitionById(id);
	}
	
	/**
	 * 删除一个流程定义
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	public @ResponseBody BaseResponse delete(String id) {
		return processDefinitionService.deleteDeploymentCascade(id);
	}
	
	/**
	 * 获取流程定义图
	 * @param response
	 * @param id
	 * @throws Exception
	 */
	@RequestMapping("/getDiagram")
	public void getDiagram(HttpServletResponse response,String id) throws Exception{
			ServletOutputStream out = response.getOutputStream();
			InputStream  image=processDefinitionService.getDiagram(id);
			response.setContentLength(image.available());
			int s;
			while((s=image.read())!=-1){
				out.write(s);
			}
	        out.close();
	}
	
	/**
	 * 分页查找
	 * @param pageable
	 * @param dto
	 * @return
	 */
	@RequestMapping("/findByPage")
	public @ResponseBody BaseResponse findByPage(@PageableDefault Pageable pageable,ProcessDefinitionQueryDto dto) {
		return processDefinitionService.findByPage(pageable, dto);
	}
	
	
	/**
	 * 通过ID获取流程定义
	 * @param id
	 * @return
	 */
	@RequestMapping("/getById")
	public @ResponseBody  BaseResponse getById(String id) {
		return processDefinitionService.getProcessDefinitionById(id);
	}
	
	
	/**
	 * 获取流程启动的表单键
	 * 用于页面跳转
	 * @param processDefinitionId
	 * @return
	 */
	@RequestMapping("/getStartFormKey")
	public @ResponseBody BaseResponse getStartFormKey(String processDefinitionId) {
		return processDefinitionService.getStartFormKey(processDefinitionId);
	}
	
	
}
